package com.zdzx.controller.admin.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.UserMapper;
import com.zdzx.mapper.UserRoleMapper;
import com.zdzx.model.service.base.param.LoginInfo;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.User;
import com.zdzx.model.service.base.vo.UserRole;
import com.zdzx.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "index")
@RestController
@RequestMapping("/admin")
public class IndexController {
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Autowired
	private UserService userService;
	
	@ApiOperation(value = "刷新token", notes = "")
	@GetMapping("/refToken")
	public Result<String> refToken(HttpServletRequest request){
		String token=request.getHeader("Authorization");
		return userService.refToken(token);
	}

	@ApiOperation(value = "登录", notes = "")
	@PostMapping("/login")
	public Result<UserInfo> login(@RequestBody LoginInfo loginInfo,HttpServletRequest request){
		loginInfo.setFrom("ADMIN");
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("account", loginInfo.getAccount());
		List<User> selectList = userMapper.selectList(queryWrapper);
		if(selectList!=null&&selectList.size()>0) {
			QueryWrapper<UserRole> queryWrapper1=new QueryWrapper<UserRole>();
			queryWrapper1.eq("user_id", selectList.get(0).getId());
			Integer selectCount = userRoleMapper.selectCount(queryWrapper1);
			if(selectCount!=null&&selectCount>0) {
				return userService.login(loginInfo,request);
			}else {
				return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "账号不存在！！！",null);
			}
		}else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "账号不存在！！！",null);
		}
		
	}
	
	@ApiOperation(value = "登出", notes = "")
	@GetMapping("/logout")
	public Result<String> loout(HttpServletRequest request){
		String token=request.getHeader("Authorization");
		return userService.logout(token);
	}
	
}
